<template>
  <div class="addForm">
    <div class="collapse">
      <h3 class="title">
        <span class="bt">*</span>
        {{ txt1 }}项目
      </h3>
      <div class="bg">
        <van-collapse v-model="activeNames">
          <template v-if="fromPath == 1">
            <van-collapse-item
              :title="v.item"
              name="1"
              v-for="v in form.spotInspectionItemsRecordParamList"
              :key="v.id"
            >
              <div class="collapse_item">
                <div class="item" v-for="item in arr" :key="item.id">
                  <p class="label">{{ item.label }}</p>
                  <p class="content">{{ v[item.key] }}</p>
                </div>
              </div>
            </van-collapse-item>
          </template>
          <template v-if="fromPath == 2">
            <van-collapse-item
              :title="v.item"
              name="1"
              v-for="v in form.maintenanceItemsRecordParamList"
              :key="v.id"
            >
              <div class="collapse_item">
                <div class="item" v-for="item in arr1" :key="item.id">
                  <p class="label">{{ item.label }}</p>
                  <p class="content">{{ v[item.key] }}</p>
                </div>
              </div>
            </van-collapse-item>
          </template>
        </van-collapse>

        <div class="collapse_item">
          <van-form @failed="onFailed" @submit="onSubmit">
            <van-cell-group>
              <van-field
                required
                is-link
                readonly
                v-model="result"
                :name="txt1 + '结果'"
                :label="txt1 + '结果'"
                :placeholder="txt1 + '结果'"
                @click="showPicker = true"
                :rules="[{ required: true, message: '巡检结果' }]"
              />

              <van-popup
                v-model:show="showPicker"
                destroy-on-close
                round
                position="bottom"
              >
                <van-picker
                  :columns="pointResult"
                  @confirm="onConfirm"
                  @cancel="showPicker = false"
                />
              </van-popup>
              <van-field
                required
                is-link
                readonly
                v-model="deviceStateList"
                name="设备状态"
                label="设备状态"
                placeholder="设备状态"
                @click="showPickerState = true"
                :rules="[{ required: true, message: '设备状态' }]"
              />

              <van-popup
                v-model:show="showPickerState"
                destroy-on-close
                round
                position="bottom"
              >
                <van-picker
                  :columns="pointState"
                  @confirm="onConfirm1"
                  @cancel="showPickerState = false"
                />
              </van-popup>
              <div>
                <p class="upload_img"><span class="bt">*</span> <span>现场图片</span></p>
                <van-uploader
                  class="custom_uploader"
                  v-model="fileList"
                  :after-read="afterRead"
                  :deletable="true"
                  :disabled="form.photoIdList.length >= 3"
                  @delete="handleDeleteFile"
                  input-accept="image/*"
                />
              </div>
              <van-field
                v-model="form.remark"
                class="custom_textarea"
                type="textarea"
                name="情况描述"
                label="情况描述"
                placeholder="情况描述"
                :rules="[{ required: false, message: '情况描述' }]"
                rows="4"
                autosize
                maxlength="200"
                show-word-limit
              />
              <van-field
                required
                is-link
                readonly
                v-model="exceptionType"
                name="异常类型"
                label="异常类型"
                placeholder="异常类型"
                @click="showPickerExceptionType = true"
                :rules="[{ required: true, message: '异常类型' }]"
              />

              <van-popup
                v-model:show="showPickerExceptionType"
                destroy-on-close
                round
                position="bottom"
              >
                <van-picker
                  :columns-field-names="{
                    text: 'name',
                    value: 'code',
                    children: 'children',
                  }"
                  :columns="exceptionOptions"
                  @confirm="onConfirm2"
                  @cancel="showPickerExceptionType = false"
                />
              </van-popup>
              <van-field
                required
                v-model="form.item"
                type="text"
                name="异常项目"
                label="异常项目"
                placeholder="异常项目"
                :rules="[{ required: true, message: '异常项目' }]"
              />

              <van-field
                required
                is-link
                readonly
                v-model="notifiedPersonList"
                name="知会人"
                label="知会人"
                placeholder="知会人"
                @click="showPickerNotifiedPersonList = true"
                :rules="[{ required: true, message: '知会人' }]"
              />

              <van-popup
                v-model:show="showPickerNotifiedPersonList"
                destroy-on-close
                round
                position="bottom"
              >
                <van-picker
                  :columns-field-names="{
                    text: 'name',
                    value: 'id',
                    children: 'children',
                  }"
                  :columns="personOptions"
                  @confirm="onConfirm3"
                  @cancel="showPickerNotifiedPersonList = false"
                />
              </van-popup>
            </van-cell-group>
            <div class="btns">
              <van-button block type="primary" native-type="submit" :disabled="disabled">
                提交
              </van-button>
              <van-button @click="handleOrder" block type="success" :disabled="disabled">
                转工单
              </van-button>
            </div>
          </van-form>
        </div>
      </div>
    </div>
    <van-overlay :show="showOverlay" class-name="loading_overlay">
      <van-loading class="loading" type="spinner" color="#1989fa" />
    </van-overlay>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { circleProps, showNotify } from 'vant';
import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();
import { getToken } from '@/utils/auth';
import {
  addSpotInspectionRecord,
  addMaintenanceRecord,
} from '@/api/maintenanceRecord.js';
import { fileUpload } from '@/api/common.js';
import { getUserAll } from '@/api/equipmentLedger.js';
import { getSpotInspectionPlanInfo } from '@/api/potInspectionPlan.js';
import { getMaintenanceInfo } from '@/api/maintenancePlan.js';
import { pointResult, pointState } from '@/utils/options.js';
import { getDictOptions } from '@/utils/dic.js';
const activeNames = ref(['2']);
const showOverlay = ref(false);
const exceptionOptions = ref([]);
const personOptions = ref([]);
const fileList = ref([]);
const showPicker = ref(false);
const showPickerState = ref(false);
const showPickerExceptionType = ref(false);
const showPickerNotifiedPersonList = ref(false);
const disabled = ref(false);
const info = ref({});
const form = reactive({
  maintenancePlanId: route.params.id || '',
  maintenanceItemsRecordParamList: [],
  spotInspectionPlanId: route.params.id || '',
  spotInspectionItemsRecordParamList: [],
  deviceId: route.params.deviceId || '',
  result: '',
  deviceStateList: [],
  photoIdList: [],
  remark: '',
  exceptionType: '',
  item: [],
  notifiedPersonList: [],
});
const result = ref([]);
const deviceStateList = ref('');
const exceptionType = ref('');
const notifiedPersonList = ref('');
const fileIds = ref([]);
const headers = {
  'Content-Type': 'multipart/form-data',
  Authorization: 'Bearer ' + getToken(),
};
const arr = [
  {
    label: '检查项目',
    key: 'item',
  },
  {
    label: '检查方法及基准',
    key: 'inspectionStandards',
  },
  {
    label: '上限',
    key: 'upperLimit',
  },
  {
    label: '下限',
    key: 'lowerLimit',
  },
  {
    label: '结果',
    key: 'remark',
  },
];
const arr1 = [
  {
    label: '检查项目',
    key: 'item',
  },
  {
    label: '方法及要求',
    key: 'methodRequirement',
  },
  {
    label: '结果',
    key: 'result',
  },
];
const txt1 = ref('巡检');
const fromPath = router.options.history.state.back == '/pointInspection' ? 1 : 2;
onMounted(async () => {
  if (fromPath == 1) {
    txt1.value = '巡检';
  } else {
    txt1.value = '保养';
  }

  await getDetail(route.params.id);
  exceptionOptions.value = await getDictOptions('exceptionType');
  await getPersons();
});

function getDetail(deviceId) {
  showOverlay.value = true;
  if (fromPath == 1) {
    //  巡检
    getSpotInspectionPlanInfo(deviceId)
      .then((res) => {
        if (res.code == 200) {
          info.value = res.data;
          const arr = [];
          res.data.spotInspectionStandardsDeviceTypeVOList.forEach((v) => {
            v.spotInspectionItemsVOList.forEach((item) => {
              arr.push(item);
            });
          });
          form.spotInspectionItemsRecordParamList = arr;
        } else {
          disabled.value = true;
        }
      })
      .catch((err) => {
        console.log('err', err);
      })
      .finally(() => {
        showOverlay.value = false;
      });
  } else {
    //  '保养';
    getMaintenanceInfo(deviceId)
      .then((res) => {
        if (res.code == 200) {
          info.value = res.data;
          const arr = [];
          res.data.maintenanceStandardsDeviceTypeVOList.forEach((v) => {
            v.maintenanceItemsVOList.forEach((item) => {
              arr.push(item);
            });
          });
          form.maintenanceItemsRecordParamList = arr;
        } else {
          // disabled.value = true;
        }
      })
      .catch((err) => {
        console.log('err', err);
      })
      .finally(() => {
        showOverlay.value = false;
      });
  }
}

const getPersons = async () => {
  const res = await getUserAll();
  if (res.code == 200) {
    personOptions.value = res.data || [];
  }
};

const onConfirm = ({ selectedOptions }) => {
  showPicker.value = false;
  result.value = selectedOptions[0].text;
  form.result = selectedOptions[0].value;
};
const onConfirm1 = ({ selectedOptions }) => {
  showPickerState.value = false;

  const str = selectedOptions.map((v) => v.text).join(',');
  const ids = selectedOptions.map((v) => v.value) || [];
  deviceStateList.value = str;
  form.deviceStateList = ids || [];
};
const onConfirm2 = ({ selectedOptions }) => {
  showPickerExceptionType.value = false;
  const str = selectedOptions.map((v) => v.name).join(',');
  const ids = selectedOptions.map((v) => v.code) || [];
  exceptionType.value = str;
  form.exceptionType = ids || [];
};
const onConfirm3 = ({ selectedOptions }) => {
  showPickerNotifiedPersonList.value = false;
  const str = selectedOptions.map((v) => v.name).join(',');
  const ids = selectedOptions.map((v) => v.id) || [];
  notifiedPersonList.value = str;
  form.notifiedPersonList = ids || [];
};

const handleOrder = async () => {
  if (route.params) {
    router.push({
      path: '/inspectionTask/3/' + route.params.id + '/' + route.params.deviceId,
    });
  }
};

const onSubmit = () => {
  showOverlay.value = true;
  if (fromPath == 1) {
    const params = {
      ...form,
    };
    delete params.maintenanceItemsRecordParamList;
    delete params.maintenancePlanId;
    addSpotInspectionRecord(params)
      .then((res) => {
        if (res.code == 200) {
          showNotify({ type: 'success', message: '成功' });
          setTimeout(router.push({ path: '/pointInspection' }), 1000);
        }
      })
      .catch((err) => {
        console.log('err', err);
        showNotify({ type: 'warning', message: err.msg || '异常' });
      })
      .finally(() => {
        showOverlay.value = false;
      });
  } else {
    const params = {
      ...form,
    };
    delete params.spotInspectionItemsRecordParamList;
    delete params.spotInspectionPlanId;
    addMaintenanceRecord(params)
      .then((res) => {
        if (res.code == 200) {
          showNotify({ type: 'success', message: '成功' });
          setTimeout(router.push({ path: '/maintenancePlan' }), 1000);
        }
      })
      .catch((err) => {
        console.log('err', err);
        showNotify({ type: 'warning', message: err.msg || '异常' });
      })
      .finally(() => {
        showOverlay.value = false;
      });
  }
};
const onFailed = (errorInfo) => {
  console.log('failed', errorInfo);
};

const handleDeleteFile = (file) => {
  const index = fileIds.value.indexOf(file.file.lastModified);
  form.photoIdList.splice(index, 1);
  fileIds.value = fileIds.value.filter((v) => {
    return v !== file.file.lastModified;
  });
};
const afterRead = (file) => {
  file.status = 'uploading';
  file.message = '上传中...';
  uploadFile(file);
  // setTimeout(() => {
  //   file.status = 'failed';
  //   file.message = '上传失败';
  // }, 1000);
};

const uploadFile = (file) => {
  const formData = new FormData();
  formData.append('file', file.file);
  fileUpload(formData)
    .then((res) => {
      if (res.code == 200) {
        showNotify({ type: 'success', message: '成功！' });
        form.photoIdList.push(res.data.id);
        fileIds.value.push(file.file.lastModified);
      } else {
        showNotify({ type: 'warning', message: '异常！' });
      }
    })
    .catch((error) => {
      console.error(error);
      showNotify({ type: 'error', message: '失败！' });
    })
    .finally(() => {
      file.status = 'done';
      file.message = '';
    });
};
</script>

<style lang="scss" scoped>
.addForm {
  padding: 24px 0;
  height: calc(100vh - 100px);
  overflow-y: auto;
  .btns {
    display: flex;
    justify-content: space-around;
    .van-button {
      width: 150px;
      height: 44px;
      border-radius: 6px 6px 6px 6px;
    }
  }
  .van-collapse-item__content {
    padding: 0;
  }
  .bg {
    background: url('@/assets/images/bg2.png') no-repeat;
    background-size: 100% 100%;
    width: 100%;
  }
  .collapse {
    margin-top: 24px;
  }
  .title {
    height: 24px;
    font-weight: bold;
    font-size: 15px;
    color: #333333;
  }

  .item {
    padding: 10px;
    .label {
      height: 24px;
      font-weight: 400;
      font-size: 14px;
      color: #333333;
      margin: 4px 0;
    }
    .content {
      padding: 0 10px;
      box-sizing: border-box;
      width: 100%;
      height: 45px;
      line-height: 45px;
      background: #f1f1f1;
      border-radius: 2px 2px 2px 2px;
      border: 1px solid #cccccc;
      font-weight: 400;
      font-size: 14px;
      color: #666666;
    }
  }
  .custom_textarea {
    ::v-deep .van-field__value {
      padding: 10px 16px;
      background: #f8f8f8;
      border-radius: 2px 2px 2px 2px;
    }
  }
}
</style>
